package com.jeesite.modules.wx.web;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.modules.common.refun.CollectionUtil;
import com.jeesite.modules.common.refun.StringUtil;
import com.jeesite.modules.wx.entity.WxActivity;
import com.jeesite.modules.wx.entity.WxBusinessUser;
import com.jeesite.modules.wx.entity.WxBusinessUserTongji;
import com.jeesite.modules.wx.entity.WxUser;
import com.jeesite.modules.wx.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author wangjianxin
 * @date 2018-09-26 10:20:34
 */
@RestController
@RequestMapping("/wx")
@Slf4j
public class WxLoginController {

    @Autowired
    private WxLoginService wxLoginService;
    @Autowired
    private WxBusinessUserTongjiService wxBusinessUserTongjiService;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private WxBusinessUserService wxBusinessUserService;
    @Autowired
    private WxActivityService wxActivityService;

    @RequestMapping("/login")
    public String login(){
        return "login";
    }


    /**
     * 授权登录入口
     *
     * 前端入口页面访问此接口
     */
    @RequestMapping("/OAuth")
    public void oauth(HttpServletResponse httpServletResponse,@RequestParam(value = "activityId") String activityId,
                      @RequestParam(value = "inviteUserOpenId",required = false) String inviteUserOpenId,
                      @RequestParam(value = "userOpenId",required = false) String userOpenId){

        try {
            // null 字符串是前端localStorage中的坑
            if(StringUtil.isNotEmpty(userOpenId) && !userOpenId.equals("null")){
                //直接重定向前端
                if(StringUtil.isEmpty(inviteUserOpenId) || userOpenId.equals(inviteUserOpenId) || inviteUserOpenId.equals("null")){
                    inviteUserOpenId = "99";
                }
                //员工游览量
                if(StringUtil.isNotEmpty(inviteUserOpenId)){
                    businessUserBrow(inviteUserOpenId,userOpenId,activityId);
                }

                httpServletResponse.sendRedirect("http://h5.wangjianxin.top/H5index/"+activityId+"/"+userOpenId+"/"+inviteUserOpenId);
                return;
            }
            //跳转授权
            httpServletResponse.sendRedirect(wxLoginService.getOAuthRedirectUrl(activityId,inviteUserOpenId,userOpenId));
        } catch (IOException e) {
            log.error("授权重定向失败={}",e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 授权登录后的重定向地址
     * @param httpServletResponse
     */
    @RequestMapping("/redirect")
    public void redirect(HttpServletResponse httpServletResponse,
                         @RequestParam(value = "code") String code,
                         @RequestParam(value = "state") String state){
        log.info("进入回调");
        log.info("回调获取到state={}",state);
        //获得地址后用于返回前端
        JSONObject result = wxLoginService.redirect(code,state);
        try {
            if(null != result){
                String openId = (String) result.get("openid");

                String inviteOpenId = "99";
                String activityId = state;
                if(state.contains(",")){
                    String[] stateArray = state.split(",");
                    activityId = stateArray[0];
                    inviteOpenId = stateArray[1];
                }

                //这里设计的员工的游览量++
                if(StringUtil.isNotEmpty(inviteOpenId)){
                    businessUserBrow(inviteOpenId,openId,activityId);
                }

                httpServletResponse.sendRedirect("http://h5.wangjianxin.top/H5index/"+activityId+"/"+openId+"/"+inviteOpenId);

            }else{
                log.error("授权回调失败");
            }
        } catch (IOException e) {
            log.error("登录授权后返回前端失败={}",e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 设计员工游览量++
     * @param inviteOpenId
     * @param openId
     * @param activityId
     */
    public void businessUserBrow(String inviteOpenId,String openId,String activityId){
        try {
            if(!inviteOpenId.equals(openId)){
                WxUser wxUser = wxUserService.findByOpenId(inviteOpenId);
                if(null != wxUser){
                    //查找他是否是员工
                    WxBusinessUser wxBusinessUser = new WxBusinessUser();
                    wxBusinessUser.setUserId(Long.valueOf(wxUser.getId()));
                    List<WxBusinessUser> wxBusinessUserList = wxBusinessUserService.findList(wxBusinessUser);
                    if(CollectionUtil.isEmpty(wxBusinessUserList)){
                        log.info("inviteOpenId不是员工");
                    }else{
                        //查看商家是否在活动当中
                        WxBusinessUser checkWxBusinesseUser = wxBusinessUserList.get(0);
                        Long businessId = checkWxBusinesseUser.getBusinessId();
                        WxActivity wxActivity = wxActivityService.get(activityId);
                        String activityBusiness = wxActivity.getBusiness();
                        String activityBusinessApply = wxActivity.getBusinessApply();
                        if(StringUtil.isNotEmpty(activityBusiness)){
                            if(activityBusiness.contains(businessId.toString()) || activityBusinessApply.contains(businessId.toString())){

                                //员工统计
                                WxBusinessUserTongji wxBusinessUserTongji = new WxBusinessUserTongji();
                                //活动
                                wxBusinessUserTongji.setActivityId(Long.valueOf(activityId));
                                //员工的openId
                                wxBusinessUserTongji.setUserOpenId(inviteOpenId);
                                List<WxBusinessUserTongji> wxBusinessUserTongjiList = wxBusinessUserTongjiService.findList(wxBusinessUserTongji);
                                if(CollectionUtil.isNotEmpty(wxBusinessUserTongjiList)){
                                    WxBusinessUserTongji temp =  wxBusinessUserTongjiList.get(0);
                                    Long youlanCount = temp.getYoulan();
                                    if(null == youlanCount){
                                        youlanCount = 0L;
                                    }
                                    temp.setYoulan(youlanCount+1L);
                                    wxBusinessUserTongjiService.save(temp);
                                }else{
                                    //员工的userId
                                    wxBusinessUserTongji.setUserId(Long.valueOf(wxUser.getId()));
                                    wxBusinessUserTongji.setYoulan(1L);
                                    //根据员工userId查询员工id
                                    wxBusinessUserTongji.setWxBusinessUserId(Long.valueOf(wxBusinessUserList.get(0).getId()));
                                    wxBusinessUserTongjiService.save(wxBusinessUserTongji);
                                }


                            }else{
                                log.info("商家不在这次活动中，员工分享++无效");
                            }
                        }
                    }
                }else{
                    log.info("用户未找到");
                }

            }else{
                log.info("自己游览自己了");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("员工游览量++错误={}",e.getMessage());
        }

    }
    /**
     *
     * @return
     */
    @RequestMapping("/getUserTest")
    public String getUserTest(){
        String ac = "14_ssLD3Z-DpE4A8nZW-4kU4feF2YikKgot8twUEetmFQZ_dWEZwPGW-aFwCIKtWIQOG6Cf42sDjDbA-fyyIH1eiw";
        String id = "osGWh0mIL5-nQkxacqgXbVE151Gk";
        wxLoginService.getUserinfo(ac,id);

        return "";

    }



}
